const express = require('express');
const router = express.Router();
const Category = require('../schemas/category');
const Content = require('../schemas/content');
const User = require('../schemas/users');
const Comment = require('../schemas/comment')

let data;
// 通用数据
router.use(async function(req, res, next){
  data = {
    userInfo: req.userInfo,
    categorys: [],
  };
  // 获取分类的信息
  let categorys = await Category.findAll();
  data.categorys = [...categorys];
  next();
})

router.get('/', async function(req, res, next){
  let page = req.query.page || 1;
  let categoryId = req.query.category || '';
  let whereObj = categoryId ? {categoryId: categoryId} : {};
  let param = await getPageParam(page, Content, whereObj);

  // 相当于是预先加载了category
  let contents = await Content.findAll({
    limit: param.take,
    offset: param.skip,
    order: [
      ["createdAt", "DESC"]
    ],
    include: [User,Category],
    where: whereObj
  });
  
  res.render('main/index', {
    contents: contents,
    category: categoryId,
    page: param.page,
    count: param.count,
    take: param.take,
    pages: param.pages,
    ...data
  });
});
router.get('/view', async function(req, res){
  let contentId = req.query.contentId || '';
  let content = await Content.findOne({
    where: { id: contentId },
    include: Comment
  });
  
  let views = content.views + 1;
  // 修改阅读数
  await Content.update({
    views: views
  },{
    where: {
      id: contentId
    }
  });

  res.render('main/view', {
    content, 
    ...data
  });
})
// 专门用来处理分页逻辑
async function getPageParam(page, Model, condition){
  condition = !condition ? {} : condition;
  let take = 3; 
  let pages = 0;

  // 获取总条数
  let count = await Model.count({where: condition});
  pages = Math.ceil(count / take);

  page = Math.min(page, pages);
  page = Math.max(page, 1);

  // 计算偏移量
  let skip = (page - 1) * take;

  return {
    page: page,
    count: count,
    take: take,
    pages: pages,
    skip: skip
  }
}

module.exports = router;